/******************************************************************************
 * Copyright (C) 2009 Peter ZHOU <peterzhoulei@gmail.com>                     *
 *                                                                            *
 * This program is free software; you can redistribute it and/or              *
 * modify it under the terms of the GNU General Public License as             *
 * published by the Free Software Foundation; either version 2 of             *
 * the License, or (at your option) any later version.                        *
 *                                                                            *
 * This program is distributed in the hope that it will be useful,            *
 * but WITHOUT ANY WARRANTY; without even the implied warranty of             *
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the              *
 * GNU General Public License for more details.                               *
 *                                                                            *
 * You should have received a copy of the GNU General Public License          *
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.      *
 ******************************************************************************/

#import "ddIM_network.h"


@implementation ddIM_network

-(id)init
{
	self = [super init];
	return self;
}

-(void)connectToServer
{
	NSLog(@"connecting to the server...");
	NSURL* url = [NSURL URLWithString:@"http://www.peterzl.net/ddim/py_peterzhoulei.txt"];
	if ( receivedData != nil )
		[receivedData release];
	receivedData = [[NSMutableData alloc] init];
	NSMutableURLRequest* urlRequest = [[NSMutableURLRequest alloc] initWithURL:url];
	//	[urlRequest setHTTPMethod:@"POST"];
	[NSURLConnection connectionWithRequest:urlRequest delegate:self];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
	NSLog([error localizedDescription]);
	NSNotificationCenter* nCenter = [NSNotificationCenter defaultCenter];
	[nCenter postNotificationName:@"ConnectionEnded" object:self userInfo:nil];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
	NSLog(@"receiving data...");
	[receivedData appendData:data];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
	NSLog(@"data ends!");
	NSString* dataContent = [[NSString alloc] initWithData:receivedData encoding:4];
	NSDate* version = [NSDate dateWithString:[dataContent substringToIndex:25]];
	extern ddIM_dict* dict;
	if ( [[dict version] compare:version] == NSOrderedAscending )
	{
		NSString *filePath  = [[NSBundle mainBundle] pathForResource:@"py" ofType:@"txt"];
		if ( [receivedData writeToFile:filePath atomically:YES] )
		{
			[dict setVersion:version];
			[dict dictionaryUpdated];
			NSLog(@"backup written");
		}
	}
	NSNotificationCenter* nCenter = [NSNotificationCenter defaultCenter];
	[nCenter postNotificationName:@"ConnectionEnded" object:self userInfo:nil];
}

@end
